package org.ogv.spritesheet;

import org.ogv.spritesheet.SpriteSheetDef.SpriteAnim;

import com.badlogic.gdx.graphics.g2d.Sprite;

public class SpriteSheet extends Sprite {

	private SpriteSheetDef 	_def;
	private SpriteAnim 		_activeAnim;
	private float			_timer;
	private int				_activeFrameIdx;
	
	public SpriteSheet init(SpriteSheetDef def) {
		_def 			= def;
		_activeFrameIdx = -1;
		setAnim(0);
		return this;
	}
	
	public void setAnim(int idx) {
		//change currently active animation
		_activeAnim = _def.animDefs[idx];
		_timer		= 0;
		
		//update frame
		update(0);
	}
	
	public void update(float delta) {
		//update timer
		_timer += delta;
		
		//change frame when necessary
		int nextFrame = _activeAnim.getKeyFrame(_timer);
		if(_activeFrameIdx != nextFrame) {
			setActiveFrame(nextFrame);
			_activeFrameIdx = nextFrame;
		}
	}
	
	public boolean isAnimEnded() { return _activeAnim.isAnimEnded(_timer); }
	
	public SpriteSheetDef getDef() {
		return _def;
	}
	
	//change currently active frame
	private void setActiveFrame(int frameIdx) {
		float prevX = this.getX();
		float prevY = this.getY();
		float prevRot = this.getRotation();
		float prevScaleX = this.getScaleX();
		float prevScaleY = this.getScaleY();
		this.set(_def.getFrame(frameIdx));
		this.setPosition(prevX, prevY);
		this.setRotation(prevRot);
		this.setScale(prevScaleX, prevScaleY);
	}
}
